<template>
  <div class="star_container">
    <MCard>
      <template #header>
        <span>{{t('starManage.one_two_root_label')}}</span>
      </template>  
    <!--   <div class="m-t-20">
        <el-input v-model="fileContent" type="textarea" :rows="10" />
      </div> -->
      <div class="m-t-20">
        <div class="config-container">
          <div class="config-row" 
               v-for="(item, key, index) in starConfigItems" :key="key">
            <div class="config-item">
              <span class="config-label">{{item.label}}</span>
              <div class="config-component">
                <el-tooltip :content="parsedEphemeris[key]" placement="top" :disabled="!parsedEphemeris[key]">
                  <component :is="item.component" :type="item.component === 'el-date-picker' ? 'datetime' : undefined" v-model="parsedEphemeris[key]" class="w-full" popper-class="starMange_Picker" />
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex  items-center gap-20px">
         <div class="global_btn" @click="triggerFileUpload">
          <el-icon><Upload /></el-icon>
          <span>{{t('starManage.import_star_config_label')}}</span>
         </div>
         <input 
           type="file" 
           ref="fileInputRef" 
           style="display: none;" 
           @change="handleFileSelected"
         />
         <!-- 刷新星历 -->
         <div class="global_btn" v-globalLoading="{handler: handleRefreshEphemeris.bind(null), text: '刷新中'}">
          <el-icon><Refresh /></el-icon>
          <span>{{t('starManage.refresh_ephemeris_label')}}</span>
         </div>
         <!-- 保存星历 -->
         <div class="global_btn" v-globalLoading="{handler: handleSaveOneTwoEphemeris.bind(null), text: '保存中'}">
          <el-icon><Setting /></el-icon>
          {{t('starManage.save_ephemeris_label')}}
         </div>
         <!-- 触发计算 -->
         <div class="global_btn" v-globalLoading="{handler: handleCalOneTwoEphemeris.bind(null), text: '计算中'}">
          <el-icon><Setting /></el-icon>
          <span>{{t('starManage.calculate_label')}}</span>
          <span class="save-tips" v-if="saveTips">{{ saveTips }}</span>
         </div>
      </div>
    </MCard>
    <el-card>
      <template #header>
        <div class="flex justify-between items-center w-100%" >
          <span class="font-bold text-16px">{{t('starManage.six_root_label')}}</span>
          <div class="global_btn" @click="handleAddEphemeris" color="#004B94">
            <el-icon><Plus /></el-icon>
            {{t('starManage.add_ephemeris_label')}}
          </div>
        </div>
      </template>
      <el-table
        :data="ephemerisList"
      >
        <el-table-column  :label="t('starManage.id_label')" prop="id" :min-width="colData.id?.width"/>
        <el-table-column :label="t('starManage.sputnik_label')" prop="sputnik" :min-width="colData.sputnik?.width"/>
        <el-table-column :label="t('starManage.date_label')" prop="date" width="158px"/>
        <el-table-column :label="t('starManage.half_len_inclinate_label')" prop="semi_major_axis" :min-width="colData.semi_major_axis?.width"/>
        <el-table-column :label="t('starManage.eccentricity_rate_label')" prop="eccentricity_rate" :min-width="colData.eccentricity_rate?.width"/>
        <el-table-column :label="t('starManage.dip_label')" prop="dip" :min-width="colData.dip?.width"/>
        <el-table-column :label="t('starManage.right_ascension_ascende_node_label')" prop="right_ascension_ascende_node" :min-width="colData.right_ascension_ascende_node?.width"/>
        <el-table-column :label="t('starManage.argument_of_perigee_label')" prop="argument_perigee" :min-width="colData.argument_perigee?.width"/>
        <el-table-column :label="t('starManage.mean_anomaly_label')" prop="mean_anoma" :min-width="colData.mean_anoma?.width"/>
        <el-table-column :label="t('starManage.site_name_label')" prop="earth_station" :min-width="colData.earth_station?.width"/>
        <el-table-column :label="t('starManage.site_longitude_label')" prop="longitude" :min-width="colData.longitude?.width"/>
        <el-table-column :label="t('starManage.site_latitude_label')" prop="latitude" :min-width="colData.latitude?.width"/>
        <el-table-column :label="t('starManage.site_height_label')" prop="height" :min-width="colData.height?.width"  />
        <el-table-column :label="t('starManage.site_visual_angle_label')" prop="visual_angle" :min-width="colData.visual_angle?.width"/>
        <el-table-column  fixed="right" align="center" :label="t('starManage.operation_label')"  min-width="150px">
          <template v-slot="{row}">
            <div class="flex justify-end items-center gap-10px">
              <div class="global_btn" text size="large" @click="handleEditEphemeris(row)">
                <el-icon><Edit /></el-icon>
                <span>{{t('starManage.operation.edit')}}</span>
            </div>
            <div class="global_btn_cancel "  v-globalLoading='handleDeleteEphemeris.bind(null,row)'>
              <el-icon><Delete /></el-icon>
              <span>{{t('starManage.delete_label')}}</span>
            </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="flex m-t-20 gap-20px w-100%">
    <el-card class="w-65% ">
      <template #header>
        <span >{{t('starManage.ephemeris_cal_label')}}</span>
      </template>
      <el-form
        :model="ephemerisCalForm"
        ref="ephemerisCalFormRef"
        :rules="ephemerisCalFormRules"
        :inline="true"     
        hide-required-asterisk
        class="search-form "
      >
        <el-form-item :label="t('starManage.sputnik_id_label')" prop="id">
          <MSelect v-bind="sputnikConfig" v-model="ephemerisCalForm.id" />
        </el-form-item>  
        <el-form-item  :label="t('starManage.start_time_label')" prop="date">
          <div class="min-w-300px">
            <el-date-picker 
              v-model="ephemerisCalForm.date" 
              type="datetime" 
              @change="handleDateChange"
              :placeholder="t('starManage.select_start_time_label')"
              popper-class="starMange_Picker"
            />
          </div>  
        </el-form-item>
        <el-form-item :label="t('starManage.forecast_duration_label')" prop="time">
          <el-input v-model.number="ephemerisCalForm.time"  :placeholder="t('starManage.input_forecast_duration_label')" />
        </el-form-item>
        <el-form-item label="" >
          <div class="global_btn" v-globalLoading="handleCalEphemeris" :loading="ephemerisCalForm.loading">
            <el-icon><Setting /></el-icon>
            {{t('starManage.calculate_label')}}
          </div>
        </el-form-item>
      </el-form>
    </el-card>
     <MCard class="w-35% ">
      <template #header>
        <span>{{t('starManage.sib2_setting_label')}}</span>
      </template>
      <el-form
        :inline="true"
      >
        <el-form-item :label="t('starManage.sib2_setting_label')" prop="sib2Set">
          <div class="switch-wrapper">
            <el-switch v-model="sib2Config.sib2" :active-value="1" :inactive-value="0" />
            <div v-if="sib2Config.sib2 === 1" class="switch-beam"></div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="global_btn" v-globalLoading="handleSib2Set">
            <el-icon><Setting /></el-icon>
            {{t('starManage.configure_label')}}
          </div>
        </el-form-item>
      </el-form>
      </MCard>
    </div>
    <el-card class="m-t-20">
      <template #header>
        <span >{{t('starManage.ephemeris_cal_status_send_status_label')}}</span>
      </template>
      <el-form :inline="true" label-suffix=" : ">
          <el-form-item :label="t('starManage.cal_status_label')">{{ephemerisStatusData.cal_status}}</el-form-item>
          <el-form-item :label="t('starManage.send_status_label')">{{ephemerisStatusData.send_status}}</el-form-item>
      </el-form>
    </el-card>
    <el-card class="m-t-20">
      <template #header>
        <span>{{t('starManage.ephemeris_record_label')}}</span>
      </template>
      <el-table
        :data="ephemerisRecordList"
        class="w-full"
        :key ='ephemerisRecordKey'
      >
        <el-table-column  :label="t('starManage.satellite_id_label')" prop="name"/>
        <el-table-column  :label="t('starManage.tracking_start_time_label')" prop="trace_begin">
          <template v-slot="{row}">
            {{formatDate(row.trace_begin)}}
          </template>
        </el-table-column>
        <el-table-column  :label="t('starManage.tracking_end_time_label')" prop="trace_end">
          <template v-slot="{row}">
            {{formatDate(row.trace_end)}}
          </template>
        </el-table-column>
        <el-table-column :label="t('starManage.antenna_label')" >
          <template v-slot="{row}">
            <MSelect
              v-bind="antennaData"
              v-model="row.ant_id"
            />
          </template>
        </el-table-column>
        <el-table-column width="300" align="center" :label="t('starManage.operation_label')" min-width="240px" fixed="right">
          <template v-slot="{row}">
            <div class="flex justify-end items-center gap-10px" >
              <MSelect
                v-bind="eRselectConfig"
                v-model="row.command"
              />
              <div class="global_btn" style="width: 80px;" v-globalLoading="handleEphemerisRecord.bind(null,row)">
                {{t('starManage.confirm_label')}}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>    
    </el-card>
    <Dialog
      v-bind="starManagedDialog"
      v-model:dialogVisible="starManagedDialog.dialogVisible"
    >    
      <template #content>
        <div class="p-20px">
          <el-form 
            ref="ephemerisFormRef"
            :model="ephemerisForm"
            :rules="ephemerisFormRules"
            class="status-form"
            label-position="right"
            label-width="auto"
          >
            <el-form-item 
              v-for="(item, key) in ephemerisLabels" 
              :key="key"
              :label="item.label"
              :prop="key"          
            >
              <el-date-picker 
                v-model="ephemerisForm[key]" 
                type="datetime" 
                v-if="key == 'date'"
                popper-class="starMange_Picker"
              />
              <el-input 
                v-else
                v-model="ephemerisForm[key]"
                :suffix="item.unit"
              />
            </el-form-item>
          </el-form>
          <div class="dialog_bottom m-t-10px">
            <div class="confirm_btn" @click="handleSaveEphemeris">
              {{t('starManage.save_label')}}
            </div>
            <div class="cancel_btn" @click="starManagedDialog.dialogVisible = false">
              {{t('starManage.cancel_label')}}
            </div>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { log } from 'node:console';
export default defineComponent({
  name: 'starManage',
})
</script>
<script setup  lang="ts">
import { StarManageApi } from '@/api/starManage';
import { useI18n } from 'vue-i18n';
import { Setting, Upload } from '@element-plus/icons-vue';
import {ElNotificationFn} from '@/utils/computedUtils'
import { formatDate,formatDateToHHMMSS} from '@/utils/computedUtils'
import dayjs from 'dayjs'
import calColWidth from '@/utils/colLabel'
import axios from 'axios'
import MSelect from '@/components/MSelect.vue'
import {HomeApi} from '@/api/home'
import cloneDeep from 'lodash/cloneDeep'
const { t } = useI18n();
const fileInputRef = ref<HTMLInputElement | null>(null);
const fileContent = ref<any>('')
const parsedEphemeris = ref<any>({})
const initParsedEphemeris = ref<any>({})
const saveTips = ref<any>(t('starManage.effective_after_saving_label'))
watch(() => parsedEphemeris.value,
  (newVal) => {
    const excludedFields = ['longitude', 'latitude', 'height', 'startTime', 'forecastDuration'];
    if (!initParsedEphemeris.value || Object.keys(initParsedEphemeris.value).length === 0) {
      saveTips.value = '';
      return;
    }
    // 创建新对象，仅包含需要比较的字段
    const filteredNew: Record<string, any> = {};
    const filteredInit: Record<string, any> = {};
    // 提取需要比较的字段
    for (const key of Object.keys(newVal)) {
      if (!excludedFields.includes(key) && newVal[key] !== undefined) {
        filteredNew[key] = newVal[key];
      }
    }
    for (const key of Object.keys(initParsedEphemeris.value)) {
      if (!excludedFields.includes(key) && initParsedEphemeris.value[key] !== undefined) {
        filteredInit[key] = initParsedEphemeris.value[key];
      }
    }
    // 使用JSON.stringify进行深度比较
    const hasChanges = JSON.stringify(filteredNew) !== JSON.stringify(filteredInit);
    // 根据是否有变化更新提示
    if (hasChanges) {
      saveTips.value = `( ${t('starManage.effective_after_saving_label')} )`
    } else {
      saveTips.value = '';
    }
  },
  { deep: true }
);
const starConfigItems = computed(()=>{
  return {
    //卫星id
    starId:{
      label:t('starManage.sputnik_id_label'),
      component:'el-input'
    },
    //倾角变化率
    inclinationChangeRate:{
      label:t('starManage.inclination_change_rate_label'),
      component:'el-input'
    },
    //卫星历元时间
    epochTime:{
      label:t('starManage.satellite_epoch_time_label'),
      component:'el-date-picker',
      type:'datetime'
    },
    //升交点赤经变化率
    ascendNodeRaChangeRate:{
      label:t('starManage.ascend_node_ra_change_rate_label'),
      component:'el-input'
    },
    //半长轴
    semiMajorAxis:{
      label:t('starManage.semi_major_axis_label'),
      component:'el-input'
    },
    //近地点幅角变化率
    perigeeArgChangeRate:{
      label:t('starManage.perigee_angle_change_rate_label'),
      component:'el-input'
    },
    //偏心率
    eccentricityRate:{
      label:t('starManage.eccentricity_rate_label'),
      component:'el-input'
    },
    //平近点角变化率
    meanAnomalyChangeRate:{
      label:t('starManage.mean_anomaly_change_rate_label'),
      component:'el-input'
    },
    //倾角
    inclination:{
      label:t('starManage.inclination_label'),
      component:'el-input'
    },
    //经度
    longitude:{
      label:t('starManage.longitude_label'),
      component:'el-input'
    },
    //升交点赤经
    ascendNodeRa:{
      label:t('starManage.ascend_node_ra_label'),
      component:'el-input'
    },
    //纬度
    latitude:{
      label:t('starManage.latitude_label'),
      component:'el-input'
    },
    //近地点幅角
    perigeeArg:{
      label:t('starManage.perigee_angle_label'),
      component:'el-input'
    },
  //高度
  height:{
    label:t('starManage.height_label'),
    component:'el-input'
  },
 //平近点角
 meanAnomaly:{
  label:t('starManage.mean_anomaly_angle_label'),
  component:'el-input'
 },
 //开始时间(北京时间)
 startTime:{
  label:t('starManage.start_time_label'),
  component:'el-date-picker',
  type:'datetime'
 },
 //半长轴变化率
 semiMajorAxisChangeRate:{
  label:t('starManage.semi_major_axis_change_rate_label'),
  component:'el-input'
 },
 //预报时长
 forecastDuration:{
  label:t('starManage.forecast_duration_label'),
  component:'el-input'
 },
 //偏心率变化率
 eccentricityRateChangeRate:{
  label:t('starManage.eccentricity_change_rate_label'),
  component:'el-input'
 },
 //卫星类型
 satelliteType:{
  label:t('starManage.satellite_type_label'),
  component:'el-input'
 }
}
})
function triggerFileUpload() {
  fileInputRef.value?.click();
}
async function postTodStatus(){
  const {data: { info } } = await HomeApi.reqPostTodStatus()
  parsedEphemeris.value.height = info.altitude
  parsedEphemeris.value.longitude = info.longitude
  parsedEphemeris.value.latitude = info.latitude
}
function handleFileSelected(event: Event) {
  const fileInput = event.target as HTMLInputElement;
  const file = fileInput.files?.[0];
  if (!file) {
    ElNotificationFn("error", t('starManage.no_file_selected'));
    return;
  }
  const reader = new FileReader();
  reader.onload = async (e) => {
    try {
      const content = e.target?.result as string;
      const fileExtension = file.name.split('.').pop()?.toLowerCase();
      if (fileExtension === 'json') {
        const parsedContent = JSON.parse(content);
        fileContent.value = parsedContent;
      } else {
        const lines = content.split('\n')[1]
        fileContent.value = lines;
        const values = lines.split(',').map((item:any)=>item.trim());
        const fieldMapping = [
          { index: 0, field: 'epochTime' },        // UTC时间 (2025-05-05T00:00:00)
          { index: 1, field: 'starId' },           // 卫星ID (521)
          { index: 2, field: 'satelliteType' },    // 卫星类型 (4)
          { index: 3, field: 'semiMajorAxis' },    // 半长轴 (-13847.32)
          { index: 4, field: 'eccentricityRate' }, // 偏心率 (8.1374258E-4)
          { index: 5, field: 'inclination' },      // 倾角 (-6.30032436E-5)
          { index: 6, field: 'ascendNodeRa' },     // 升交点赤经 (0.214023783)
          { index: 7, field: 'perigeeArg' },       // 近地点幅角 (0.509478644)
          { index: 8, field: 'meanAnomaly' },      // 平近点角 (-0.176562032)
          { index: 9, field: 'semiMajorAxisChangeRate' },    // 半长轴变化率 (0.0162377106999999998)
          { index: 10, field: 'eccentricityRateChangeRate' }, // 偏心率变化率 (-3.50990092E-15)
          { index: 11, field: 'inclinationChangeRate' },      // 倾角变化率 (-7.46534401E-12)
          { index: 12, field: 'ascendNodeRaChangeRate' },     // 升交点赤经变化率 (-2.427998E-7)
          { index: 13, field: 'perigeeArgChangeRate' },       // 近地点幅角变化率 (0.0)
          { index: 14, field: 'meanAnomalyChangeRate' }       // 平近点角变化率 (-3.61293266E-27)
        ];
        const parsedObject: Record<string, string|number> = {};
        fieldMapping.forEach(mapping => {
          if (values.length > mapping.index) {
            parsedObject[mapping.field] = values[mapping.index].trim();
          }
        });   
        parsedObject.startTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        parsedObject.forecastDuration = 24
        parsedEphemeris.value = parsedObject;
        postTodStatus()
      }
      fileInput.value = '';
    } catch (error) {
      console.error('文件解析失败:', error);
      ElNotificationFn("error", t('starManage.parse_file_error'));
    }
  };
  reader.onerror = () => {
    ElNotificationFn("error", t('starManage.read_file_error'));
  };
  reader.readAsText(file);
}
async function handleSaveOneTwoEphemeris(){
  try {
    if(!parsedEphemeris.value.starId) {
      ElNotificationFn("error",t('starManage.no_data_label'))
      return
  }
  const data = cloneDeep(parsedEphemeris.value)
  data.epochTime = dayjs(data.epochTime).valueOf().toString()
  data.startTime = dayjs(data.startTime).valueOf().toString()
  data.forecastDuration = data.forecastDuration.toString()
  data.satelliteType = data.satelliteType.toString()
  data.latitude = data.latitude.toString()
  data.longitude = data.longitude.toString()
  data.height = data.height.toString()
  await StarManageApi.reqPostOneTwoRootConfig(data)
  ElNotificationFn("success",t('starManage.save_ephemeris_success_label'))
  await handleGetOneTwoEphemeris()
  } catch (error) {
    ElNotificationFn("error",t('starManage.save_ephemeris_error_label'))
  }
}
async function handleCalOneTwoEphemeris(){
  try {
    await StarManageApi.reqPostOneTwoRootCal()
    ElNotificationFn("success",t('starManage.cal_ephemeris_success_label'))
  } catch (error) {
    ElNotificationFn("error",t('starManage.cal_ephemeris_error_label'))
  }
}
async function handleGetOneTwoEphemeris(){
  const {data} = await StarManageApi.reqPostOneTwoRootGet()
  data.epochTime = Number(data.epochTime)
  data.startTime = Number(data.startTime)
  initParsedEphemeris.value = cloneDeep(data)
  parsedEphemeris.value = data
}
async function handleRefreshEphemeris(){
  try {
    await handleGetOneTwoEphemeris()
    ElNotificationFn("success",t('starManage.refresh_ephemeris_success_label'))
  } catch (error) {
    ElNotificationFn("error",t('starManage.refresh_ephemeris_error_label'))
  }
}
async function handleGetSib2(){
  try {
    const {data} = await StarManageApi.reqPostSib2Get()
    sib2Config.value.sib2 = data.sib2
  } catch (error) {}
}
async function handleSib2Set(){
  try {
    await StarManageApi.reqPostSib2Set(sib2Config.value)
    ElNotificationFn("success",t('starManage.configure_success_label'))
    handleGetSib2()
  } catch (error) { }
}
const sib2Config = ref<any>({
  sib2:0
})
const ephemerisLabels = computed<any>(() => {
  return {
    sputnik: {
      label: t('starManage.sputnik_label'),
      unit: ""
    },
    date: {
      label: t('starManage.date_label'),
      unit: ""
    },
    longitude: {
      label: t('starManage.site_longitude_label'),
      unit: "°"
    },
   
    semi_major_axis: {
      label: t('starManage.half_len_inclinate_label'),
      unit: ""
    },
  
    latitude: {
      label: t('starManage.site_latitude_label'),
      unit: "°"
    },
    eccentricity_rate: {
      label: t('starManage.eccentricity_rate_label'),
      unit: ""
    },
    height: {
      label: t('starManage.site_height_label'),
      unit: "(m)"
    },
   
    dip: {
      label: t('starManage.dip_label'),
      unit: "°"
    },
    visual_angle: {
      label: t('starManage.site_visual_angle_label'),
      unit: "°"
    },
    right_ascension_ascende_node: {
      label: t('starManage.right_ascension_ascende_node_label'),
      unit: "°"
    },
    earth_station: {
      label: t('starManage.site_name_label'),
      unit: ""
    },
    argument_perigee: {
      label: t('starManage.argument_of_perigee_label'),
      unit: "°"
    },
    mean_anoma: {
      label: t('starManage.mean_anomaly_label'),
      unit: "°"
    },
  }
})
const ephemerisList = ref<any>([]);
const colData = ref<any>({});
const colLabelFn = ()=>{
  const colLable = {
  id:t('starManage.id_label'),
  date:t('starManage.date_label'),
  eccentricity_rate:t('starManage.eccentricity_rate_label'),
  semi_major_axis:t('starManage.half_len_inclinate_label'),
  dip:t('starManage.dip_label'),
  right_ascension_ascende_node:t('starManage.right_ascension_ascende_node_label'),
  argument_perigee:t('starManage.argument_of_perigee_label'),
  mean_anoma:t('starManage.mean_anomaly_label'),
  name:t('starManage.site_name_label'),
  longitude:t('starManage.site_longitude_label'),
  latitude:t('starManage.site_latitude_label'),
  height:t('starManage.site_height_label'),
  visual_angle:t('starManage.site_visual_angle_label'),
  sputnik:t('starManage.sputnik_label'),
}
  return calColWidth(colLable,ephemerisList.value)
}
async function postEphemerisList() {
   const {data:{list}} = await StarManageApi.reqPostEphemeris();
   ephemerisList.value = list.map((item:any)=>{
    item.date = formatDateToHHMMSS(item.date)
    return item
   })
}
const sputnikConfig = computed(()=>{
  return {
    options:ephemerisList.value.map((item:any)=>{
      return {label:item.id,value:item.id}
    }),
    placeholder:t('starManage.select_sputnik_id_label'),
    width:'200px'
  }
})
const starManagedDialog = ref<any>({
  title:'',
  width:'50%',
  dialogVisible:false,
  top:"",
  changeType:"ephemeris"
})
const ephemerisForm = ref<any>({})
const ephemerisFormRef = ref<any>(null)
const ephemerisFormRules = computed(() => {
  const rules: any = {}
  Object.keys(ephemerisLabels.value).forEach(key => {
    rules[key] = [
      { 
        required: true, 
        message: ephemerisLabels.value[key].label, 
        trigger: 'blur' 
      }
    ]
  })
  return rules
})
async function handleAddEphemeris(){
  if(ephemerisList.value.length) {
    ephemerisForm.value = ephemerisList.value[ephemerisList.value.length - 1]
    delete ephemerisForm.value.id
  }else{
    ephemerisForm.value = {}
  }
  starManagedDialog.value.title = t('starManage.add_ephemeris_label')
  starManagedDialog.value.dialogVisible = true
}
async function handleSaveEphemeris(){
  try {
    await ephemerisFormRef.value.validate()
    ephemerisForm.value.date = dayjs(ephemerisForm.value.date).valueOf()
    await StarManageApi.reqPostEphemerisSet(ephemerisForm.value)
    starManagedDialog.value.dialogVisible = false
    await postEphemerisList()
    ElNotificationFn("success",t('starManage.set_success_label'))
  } catch (error) {
    console.log(error);   
  }
}
function handleEditEphemeris(row:any){
  ephemerisForm.value = {...row}
  starManagedDialog.value.title = t('starManage.edit_ephemeris_label')
  starManagedDialog.value.dialogVisible = true
}
const ephemerisCalForm = ref<any>({
  date:"",
  time:'',
  id:'',
  loading:false
})
const ephemerisCalFormRef = ref<any>(null)  
const ephemerisCalFormRules = computed<any>(()=>{
   return {
    date:[
      {required:true,message:t('starManage.start_time_label'),trigger: ['change', 'blur'] }
    ],
    time:[
      {required:true,message:t('starManage.forecast_duration_label'),trigger:'blur'},
      {type:'number',message:t('starManage.number_label'),trigger:'blur'}
    ],
    id:[
      {required:true,message:t('starManage.sputnik_label'),trigger:'change'}
    ]
   }
})
function handleDateChange(val:any){
  ephemerisCalForm.value.date = dayjs(val).format('YYYY-MM-DD HH:mm')
}
async function handleCalEphemeris(){
  try {
    await ephemerisCalFormRef.value.validate()
    ephemerisCalForm.value.loading = true
    ephemerisCalForm.value.date = dayjs(ephemerisCalForm.value.date).valueOf()
    await StarManageApi.reqPostEphemerisCal({
      date:ephemerisCalForm.value.date,
      time:ephemerisCalForm.value.time,
      id:ephemerisCalForm.value.id
    })
    ElNotificationFn("success",t('starManage.set_success_label'))
  } catch (error) {
  }
  ephemerisCalForm.value.loading = false
}
const ephemerisRecordList = ref<any>([])
const ephemerisRecordKey = ref<any>(0)
const ephemerisStatusData = ref<any>({
  cal_status:'',
  send_status:''
})
async function postEphemerisRecordList(){
  const {data} = await StarManageApi.reqPostEphemerisRecord()
  ephemerisStatusData.value.cal_status = data.cal_status
  ephemerisStatusData.value.send_status = data.send_status
  if(ephemerisRecordList.value.length === 0) {
    ephemerisRecordList.value = data.record.map((item:any)=>{
      item.command = ''
      item.ant_id = ''
      return item
    })
  } else {
    ephemerisRecordList.value = data.record.map((item:any)=>{
      const existingItem = ephemerisRecordList.value.find(
        (existing:any) => existing.id === item.id
      )
      return {
        ...item,
        command: existingItem ? existingItem.command : '',
        ant_id: existingItem ? existingItem.ant_id : ''
      }
    })
  }
  ephemerisRecordKey.value++
}
const eRselectConfig = computed(()=>{
  return {
    options:[
      {label:t('starManage.send_ephemeris_label'),value:'send'},
      {label:t('starManage.send_and_cut_label'),value:'send_and_swtich'},
      {label:t('starManage.info_label'),value:'detail'},
      {label:t('starManage.delete_label'),value:'delete'}
    ],
    placeholder:t('starManage.operation_label')
  }
})
async function handleEphemerisRecord(row:any){
  if(row.command===''){
    ElNotificationFn("warning","请选择操作")
    return
  }

  if(row.ant_id===undefined){
    row.ant_id = ''
  }
  if((row.command==='send'||row.command==='send_and_swtich')&&(row.ant_id==='')){
    ElNotificationFn("warning","发送星历需选择天线")
    return
  }
  const {data} =  await StarManageApi.reqPostEphemerisControl({
    id:row.id,
    command:row.command,
    ant_id:row.ant_id
  })
  if(row.command === 'detail') {
    const response = await axios({
      url:data.data
    })
    const blob = new Blob([response.data])
    const a = document.createElement('a')
    a.href = window.URL.createObjectURL(blob)
    a.download = `${row.name}_${t('starManage.detail_label')}.log`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(a.href)
    ElNotificationFn("success",t('starManage.set_success_label'))
    return 
  }
  ElNotificationFn("success",t('starManage.set_success_label'))
}
const antennaData = ref<any>({
  options:[
    {label:t('starManage.antenna_a_label'),value:0},
    {label:t('starManage.antenna_b_label'),value:1},
  ],
  placeholder:t('starManage.antenna_label')
})
async function handleDeleteEphemeris(row:any){
  try {
    await StarManageApi.reqPostEphemerisDelete({ 
      id:row.id
    })
    ElNotificationFn("success",t('starManage.delete_success_label'))
    await postEphemerisList()
  } catch (error) {
    ElNotificationFn("error",t('starManage.delete_error_label'))
  }
}

const fetchTasks = [
  {fn:postEphemerisRecordList,name:"获取星历记录"},
]
let initTimer:any = null
let isUpdating = false 
async function init(){
  if (isUpdating) return  
  isUpdating = true 
  try {
    const results = await Promise.allSettled(
      fetchTasks.map(task => task.fn())
    )  
    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        console.error(`获取${fetchTasks[index].name}失败:`, result.reason)
      }
    })
  } finally {
    isUpdating = false 
  }
}
function scheduleNextUpdate() {
  initTimer = window.setTimeout(() => {
    init().finally(() => {
      if (initTimer) { 
        scheduleNextUpdate()
      }
    })
  }, 5000)
}
onMounted(async() => {
    postEphemerisList()
    postEphemerisRecordList()
    handleGetOneTwoEphemeris()
    handleGetSib2()
    scheduleNextUpdate()
    window.addEventListener('resize', async () => {
      await nextTick()
      colData.value = colLabelFn()
    })
})
watch(
  [ephemerisList,()=>t('starManage.date_label')],
  async ()=>{
    await nextTick()
    colData.value = colLabelFn()
  },
  {deep:true}
)
onBeforeUnmount(()=>{
  clearTimeout(initTimer)
})



</script>

<style  lang="scss" scoped>
@import '@/styles/table.scss';
@import '@/styles/form.scss';
@import '@/styles/input.scss';
@import '@/styles/card.scss';
@import '@/styles/switch.scss';
.star_container {
  padding: 20px;
  .search-form {
    .el-form-item {
      margin-bottom: 16px;
      margin-right: 16px;
    }
  }
}

.el-button{
  color: #00D4FF;
}
.delete_btn{
  color: #FF0000;
}
.dialog_bottom{
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.m-t-20 {
  margin-top: 20px;
}

.config-container {
  display: flex;
  flex-wrap: wrap;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  width: 100%;
}

.config-row {
  display: flex;
  width: 50%;
  padding: 10px 10px;
  box-sizing: border-box;
  background-color: #03204b;
}

.config-row:nth-child(4n+1),
.config-row:nth-child(4n+2) {
  background-color: #011e45;
}

.config-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.config-label {
  color: white;
  margin-right: 15px;
  min-width: 90px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
  font-size: 14px;
}

.config-component {
  flex: 1;
  min-width: 200px;
  max-width: 250px;
}

// 添加输入框样式
:deep(.el-input__inner) {
  background-color: #0a2c5e;
  border-color: #164785;
  color: #fff;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #142848;
  color: #8e9dbb;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

.save-tips {
  color: #ffae00;
  font-weight: bold;
  margin-left: 8px;
  padding: 2px 8px;
  border-radius: 4px;
  background-color: rgba(255, 174, 0, 0.15);
  border: 1px solid rgba(255, 174, 0, 0.3);
  animation: blink 2s infinite;
}

@keyframes blink {
  0% { opacity: 1; background-color: rgba(255, 174, 0, 0.15); }
  50% { opacity: 0.8; background-color: rgba(255, 174, 0, 0.25); }
  100% { opacity: 1; background-color: rgba(255, 174, 0, 0.15); }
}

</style>
